/*
 *  Copyright 2011 yura.
 *
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */

package org.opu.vcforms.actions;

import java.awt.event.ActionEvent;
import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import org.opu.vcforms.bean.ApplicationData;
import org.opu.vcforms.bean.Template;
import org.opu.vcforms.bean.db.ConfigPath;
import org.opu.vcforms.bean.model.ModelAvailableSource;
import org.opu.vcforms.datasource.Storage;
import org.opu.vcforms.editor.EditViewFactory;
import org.opu.vcforms.io.FileIO;
import org.opu.vcforms.template.TxtTemplate;
import org.opu.vcforms.transform_t2d.MainProcessor;
import org.opu.vcforms.transform_t2d.text.Transformer;
import org.opu.vcforms.view.component.GUIProperties;

/**
 *
 * @author yura
 */
public class Statement extends AbstractAction{

    public static final String LINE_SEPARATOR_PROP =
            MainProcessor.SYSTEM_PREFIX + MainProcessor.LINE_SEPARATOR;
    /** My name */
    public static final String MNAME = "Statement";
    private static final long serialVersionUID = -3531663983228540551L;
    private static final boolean NOW_ERROR = Boolean.parseBoolean(
            System.getProperty(ConfigPath.NOW_ERROR_PROPERTIES));

    private ApplicationData data;

    public Statement(ApplicationData data) {
        this.data = data;
    }

    @Override
    public String getName() {
        return MNAME;
    }

    @Override
    public void actionPerformed(ActionEvent e) {
        // 1) prepare input template
        Template template = data.getTemplate();
        /*Document*/TxtTemplate doc = template != null? template.getTemplate(): null;

        if (doc == null){
            errorMsg(new NullPointerException("Template is null !"));
            if (NOW_ERROR){
//                doc = new Document();
                doc = new TxtTemplate();
            } else {
                return;
            }
        }

        // 2) create output file from input template
        ModelAvailableSource source = data.getSource();

        List<String> groups = source.getGroups().getSelectedGroup();
        String facult = String.valueOf(source.getFaculties().getSelectedItem());
        int semestr = source.getSemestrs().getSelectedItem();
        int course = source.getCourses().getSelectedItem();

        Map<String, Storage> smap = new LinkedHashMap<String, Storage>();
        smap.put("groups", new Storage(set(groups)));

        Properties prop = new Properties();
        prop.setProperty("Facultet", String.valueOf(facult));
        prop.setProperty("Semestr", String.valueOf(semestr(semestr, course)));
        prop.setProperty("Course", String.valueOf(course));
        prop.setProperty(LINE_SEPARATOR_PROP, System.getProperty("line.separator"));

        // old variant {
//        Transformer transf = new Transformer(data.getDbManager(), smap, prop);
//
//        Document out = null;
//
//        try {
//            out = transf.transform(doc);
//        } catch (Exception ex) {
//            errorMsg(new RuntimeException("Can transform data: ", ex));
//            if (NOW_ERROR){
//                out = doc;
//            } else {
//                return;
//            }
//        }
//
//        // 3) create text file from result
//        TextDocumentWriter writer = new TextDocumentWriter(out);
//        StringWriter sw = new StringWriter();
//        File file = ConfigPath.getInstance().getWhereToStoring(template, course, groups);
//        try {
//            writer.write(sw);
//            FileIO.write(sw.toString(), file);
//        } catch (IOException ex) {
//            errorMsg(new RuntimeException("Can create file: ", ex));
//            if (NOW_ERROR){
//                // some extra work ...
//            } else {
//                return;
//            }
//        }
        // } old variant

        // new variant {
        Transformer transf = new Transformer(data.getDbManager(), smap, prop);
        String string = transf.transform(doc);

        // 3) create text file from result
        File file = ConfigPath.getInstance().getWhereToStoring(template, course, groups);
        try {
            FileIO.write(string, file);
        } catch (IOException ex) {
            errorMsg(new RuntimeException("Can create file: ", ex));
            if (!NOW_ERROR){
                return;
            }
        }
        // } new variant

        // 4) View result
        EditViewFactory vf = GUIProperties.instance().editor.getViewFactory();
        vf.createView(string, facult + " - " + course, file);
    }

    Set<Map> set(List<String> lst){
        Set<Map> set = new LinkedHashSet<Map>();
        for (String s : lst) {
            set.add(map(s));
        }
        return set;
    }

    Map<String, String> map(String str){
        Map<String, String> dmap = new LinkedHashMap<String, String>();
        dmap.put(str, str);
        return dmap;
    }

    int semestr(int semestr, int course){
        return course * 2 - 2 + semestr;
    }
}
